﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XAgent;

namespace LogCPU
{
    public class LogCPUService : AgentServiceBase<LogCPUService>
    {
        #region 属性

        /// <summary>显示名</summary>
        public override string DisplayName => "记录cpu占用率";
        /// <summary>描述</summary>
        public override string Description => "记录cpu占用率";

        bool isruning = true;
        #endregion
        #region 构造函数
        /// <summary>实例化一个代理服务</summary>
        public LogCPUService()
        {                // 一般在构造函数里面指定服务名
            ServiceName = "LogCPUService";
            Intervals[0] = 5;
            GetCputime();
        }

        #endregion
        public override bool Work(int x)
        {
            //Console.WriteLine($"========={x}");

            //读取配置
            var FileName = AppDomain.CurrentDomain.BaseDirectory + "Config/Process.txt";
            var str = File.ReadAllText(FileName);
            //GetCputime(str);
            var processlist = str.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (processlist.Length > 0)
                foreach (var item in processlist)
                {
                    UsingProcess(item);
                }
            return false;
        }

        TimeSpan prevCpuTime = TimeSpan.Zero;
        int interval = 5000;
        void UsingProcess(string pname)
        {
            var pros = Process.GetProcessesByName(pname);
            if (pros == null || pros.Length == 0)
            {
                return;
            }
            try
            {
                using (var pro = pros[0])
                {
                    //间隔时间（毫秒）
                    //上次记录的CPU时间
                    //while (true)
                    {
                        //当前时间
                        var curTime = pro.TotalProcessorTime;
                        //间隔时间内的CPU运行时间除以逻辑CPU数量
                        var value = (curTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
                        prevCpuTime = curTime;
                        //输出
                        //Console.WriteLine(value);
                        WriteLine($"{pname}:{value}");
                        //Thread.Sleep(interval);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLine($"取数据异常，{ex.Message}");
            }
        }
        /// <summary>
        /// 使用计数器
        /// </summary>
        /// <param name="pname"></param>
        void UsingPerfmon(string pname)
        {
            //创建性能计数器
            using (var p1 = new PerformanceCounter("Process", "% Processor Time", pname))
            {
                while (true)
                {
                    //注意除以CPU数量
                    Console.WriteLine(p1.NextValue() / Environment.ProcessorCount);
                    Thread.Sleep(1000);
                }
            }
        }

        void GetCputime(string str = "")
        {
            try
            {
                var processlist = str.Split(';');
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");

                WriteLine("-----------------------------------");
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (str == "" || processlist.Contains(queryObj["Name"]))
                    {
                        WriteLine($"Name: {queryObj["Name"]} ProcessorTime: {queryObj["PercentProcessorTime"]}");
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLine($"取数据异常，{ex.Message}");
            }
        }

        /// <summary>停止服务</summary>
        /// <param name="reason"></param>
        //public override void StopWork()
        //{
        //    base.StopWork();
        //}
    }

}
